<!DOCTYPE HTML>
<html lang="cn" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <%include("/common/header.html",{title:''}){}%>
    <title>施工团队</title>
    <style>
    </style>
</head>
<script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=IENn7ABARjQIkTeAKyh80VTkg2jYXf3K"></script>
<body>


<div class="x-nav" style="margin: 20px auto auto 15px;">
      <span class="layui-breadcrumb" lay-filter="breadcrumb" style="visibility: visible;">
        <a href="javascript:">首页</a><span lay-separator="">/</span>
        <a href="javascript:">施工团队</a><span lay-separator="">/</span>
        <a><cite>考勤管理</cite></a>
      </span>
    <a class="layui-btn layui-btn-primary layui-btn-small" style="margin: -5px 14px 0px 0px;float:right;"
       href="javascript:location.replace(location.href);" title="刷新">
        <i class="layui-icon layui-icon-refresh-3"></i>
    </a>
</div>
<div class="x-body" style="margin: 20px auto auto 15px;">
    <div class="layui-row">
        <div class="layui-form layui-col-md12 x-so">
            <a href="base/link/@/constructionTeam/att_management/att_management.jhtml" class="layui-btn layui-btn-warm">考勤列表</a>
            <a href="base/link/@/constructionTeam/att_management/checkwork.jhtml" class="layui-btn">考勤逐日统计</a>
            <% if (session.om_user.sysRole.sysRoleCode.id==2||session.om_user.sysRole.sysRoleCode.id==3){%>
            <a href="base/link/@/constructionTeam/att_management/checkwork_month.jhtml" class="layui-btn">考勤月平均值统计</a>
            <%}%>
        </div>
    </div>

    <div style="margin-left: -15px;" class="layui-form layui-card-header layuiadmin-card-header-auto">
        <div class="layui-form-item">
            <% if (session.om_user.sysRole.sysRoleCode.id==3){%>
            <input type="hidden"  value="${session.area.id}" id="area_id">
            <%}%>
            <div class="layui-input-inline">
                <input type="text" name="starttime" id="startTime" placeholder="查询开始时间" autocomplete="off" class="layui-input" >
            </div>
            <div class="layui-input-inline" style="width: auto;">
                ~
            </div>
            <div class="layui-input-inline">
                <input type="text" id="endTime" name="endtime" placeholder="查询结束时间" autocomplete="off" class="layui-input" >
            </div>
            <% if (session.om_user.sysRole.sysRoleCode.id==2||session.om_user.sysRole.sysRoleCode.id==3){%>
            <div class="layui-input-inline" >
                <select type="text" name="a_name" id="a_name1" autocomplete="off" class="layui-select">
                </select>
            </div>
            <%}%>

            <div class="layui-input-inline">
                <button  class="layui-btn layui-btn-checked" lay-submit="" lay-filter="LAY-user-front-search"  ><i class="layui-icon layui-icon-search"></i>查询</button>
            </div>
        </div>
    </div>

    <div class="layui-table-main layui-form" style="height: 100%">
        <table id="myTableData" lay-filter="myTableData"  class="layui-hide"></table>
        <div id="test1"></div>
    </div>
</div>
<!--考勤列表-->
<div class="layui-fluid">
    <div class="layui-card">
        <table id="LAY-user-manage" lay-filter="LAY-user-manage"></table>
        <% if (session.om_user.sysRole.sysRoleCode.id==4){%>
        <script type="text/html" id="toolbarDemo">
            <a class="layui-btn layui-btn layui-btn-sm"  lay-event="add"><i class="layui-icon layui-icon-add-1"></i>添加考勤</a>
        </script>
        <%}%>
        <script type="text/html" id="table-useradmin-webuser">
            <a class="layui-btn layui-bg-green layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
        </script>
    </div>
</div>
<!-- 弹出考勤页面 -->
<div class="layui-form" lay-filter="layuiadmin-form-useradmin"
     id="layuiadmin-form-useradmin"
     style="padding: 15px;display: none">
    <form action class="layui-form" lay-filter="component-form-element" id="myform">
        <input type="hidden" name="id" id="id">
        <input type="hidden" name="a_createDate" id="a_createDates">
        <input type="hidden" name="a_am_picture" id="a_am_picture">
        <input type="hidden" name="a_pm_picture" id="a_pm_picture">
        <input type="hidden"  value="${session.om_user.enterprise.id}" id="e_id" name="a_eid">
        <input type="hidden"  value="${session.om_user.team_id}" id="a_tid" name="a_tid">
        <input type="hidden"  value="${session.om_user.projectid}" id="projectid" name="a_project_id">
        <input type="hidden"  value="${session.om_user.areaid}" id="areaid" name="a_area_id">
        <input type="hidden"  value="${session.om_user.sysRole.sysRoleCode.id}" id="role_id">
        <div class="layui-form-item">
            <div class="layui-col-md6" style="float: left;margin-left: -15px;">
                <label class="layui-form-label">*日期：</label>
                <div class="layui-input-block">
                    <input id="a_createDate" type="text" name="a_createDate" lay-verify="required" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-col-md6" style="float: left">
                <label class="layui-form-label">*施工队伍：</label>
                <div class="layui-input-block">
                    <input type="text" disabled name="a_name" id="a_name" lay-verify="required" autocomplete="off" value="" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-col-md6" style="float: right;margin-right: 15px;">
                <label class="layui-form-label">*应到人数：</label>
                <div class="layui-input-block">
                    <input id="a_should_num" type="text" name="a_should_num" lay-verify="required|number" autocomplete="off" class="layui-input" placeholder="请输入应到人数...">
                </div>
            </div>
        </div>
        <h2>上午</h2><hr />
        <div class="layui-form-item">
            <div class="layui-col-md6" style="float: left;margin-top: 50px;">
                <label class="layui-form-label">*人数：</label>
                <div class="layui-input-block">
                    <input type="text" name="a_am_num" id="a_am_num" lay-verify="required|number" autocomplete="off" placeholder="请输入上午人数..." class="layui-input">
                </div>
                <div id="am">
                    <br><br><br>
                    <label class="layui-form-label">*签到时间：</label>
                    <div class="layui-input-block">
                        <input id="a_createDate2" disabled type="text" name="a_am_createDate" autocomplete="off" class="layui-input">
                    </div>
                </div>
            </div>

            <div class="layui-col-md6" style="float: left">
                <div class="layui-inline">
                    <label class="layui-form-label" style="margin-top: 50px;">*图片：</label>
                    <div class="layui-input-inline" style="width: 130px;">
                        <div class="layui-upload-list">
                            <img class="layui-upload-img" style="width: 130px;height: 130px;" id="demo1"/>
                            <p id="demoText"></p>
                        </div>
                        <button style="width: 130px;" type="button" class="layui-btn layui-btn-warm" id="upload1">上传图片</button>
                    </div>
                </div>
            </div>
        </div>
        <div id="a_pm">
            <h2>下午</h2><hr />
            <div class="layui-form-item">
                <div class="layui-col-md6" style="float: left;margin-top: 50px;">
                    <label class="layui-form-label">*人数：</label>
                    <div class="layui-input-block">
                        <input type="text" name="a_pm_num" id="a_pm_num" lay-verify="required|number" autocomplete="off" placeholder="请输入下午人数..." class="layui-input">
                    </div>
                    <div id="pm">
                        <br><br><br>
                        <label class="layui-form-label">*签到时间：</label>
                        <div class="layui-input-block">
                            <input id="a_createDate3" disabled type="text" name="a_pm_createDate" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>

                <div class="layui-col-md6" style="float: left">
                    <div class="layui-inline">
                        <label class="layui-form-label" style="margin-top: 50px;">*图片：</label>
                        <div class="layui-input-inline" style="width: 130px;">
                            <div class="layui-upload-list">
                                <img class="layui-upload-img" style="width: 130px;height: 130px;" id="demo11"/>
                                <p id="demoText1"></p>
                            </div>
                            <button style="width: 130px;" type="button" class="layui-btn layui-btn-warm" id="upload11">上传图片</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block" style="margin-left: 250px;margin-top: 50px;">
                <button class="layui-btn" lay-submit="" lay-filter="component-form-element">立即提交</button>
            </div>
        </div>
    </form>
</div>
<script id="demo4" type="text/html">
    <option value="">请选择施工队</option>
    {{#  layui.each(d.list4, function(index, item4){ }}

    <option value="{{ item4.t_name }}">{{ item4.t_name }}</option>

    {{#  }); }}
    {{#  if(d.list4.length === 0){ }}
    无数据
    {{#  } }}
</script>
<%include("/common/foot.html"){}%>
<script>
    layui.use(['index', 'table', 'form', 'laydate', 'layedit', 'AjaxCommon', 'AliangLayui'], function () {
        var $ = layui.$;
        var table = layui.table;
        var form = layui.form;
        var laydate = layui.laydate;
        var AjaxCommon = layui.AjaxCommon;

        var title = "添加考勤";
        var findAll_url = 'system/att_management/findAll.json';
        var update_url = 'system/att_management/update.json';
        var delete_url = 'system/att_management/delete.json';
        var cols = [ //考勤列表表头
            /*{checkbox: true, fixed: true},*/
            {
                totalRowText: '合计：',
                unresize: true,
                field: 't_createDate',
                sort:'true' ,
                fixed: 'left',
                templet: "<div>{{layui.util.toDateString(d.a_createDate, 'yyyy-MM-dd ')}}</div>",
                title: '考勤日期',
            },
            {field: 'a_name', sort:'true' , title: '施工队伍',},
            {field: 'a_should_num', sort:'true' , title: '应到人数',totalRow: true},
            {
                field: 'a_am_num',
                title: '上午到岗人数',
                sort:'true' ,
                totalRow: true,
                // templet: "<div>{{d.a_pm_num==null||d.a_pm_num==''?parseInt(d.a_am_num):parseInt(d.a_pm_num)}}</div>",
            },
            {
                field: 'a_pm_num',
                title: '下午到岗人数',
                sort:'true' ,
                totalRow: true,
                templet: "<div>{{d.a_pm_num==null||d.a_pm_num==''?'<p style='color: red'>未考勤</p>':parseInt(d.a_pm_num)}}</div>",
            },
            {
                field: 'a_am_picture',
                title: '图片',
                templet: function (d) {
                         return "<div class='layer-photos'><img layer-src="+(d.a_pm_picture==null||d.a_pm_picture==''?d.a_am_picture:d.a_pm_picture)+" src="+(d.a_pm_picture==null||d.a_pm_picture==''?d.a_am_picture:d.a_pm_picture)+" style='width:30px;height:30px' ></div>"
                       }},
            {title: '操作', fixed: 'right', toolbar: '#table-useradmin-webuser',}
        ];

        //查询当日当前队伍是否已拥有考勤
        var roid = $("#role_id").val();
        var tid = $("#a_tid").val();
        if(roid==4){
            $.ajax({
                url: "system/att_management/findatt_manage.json",
                type: "POST",
                data: {
                    a_tid: tid,
                    role_id: roid
                },
                dataType: "text",
                success: function (ret) {
                    if(ret==0){
                        table.render({
                            elem: '#LAY-user-manage',
                            id: 'listReload',
                            title: title,
                            url: findAll_url,
                            page: true, //开启分页
                            limits: [10, 20, 30, 50], //控制多少行一页（默认五条一页）
                            totalRow: true,//开启合计行
                            defaultToolbar: ['filter', 'print', 'exports'],
                            cols: [cols],
                            where:{
                                a_tid:$("#a_tid").val(),
                                role_id:$("#role_id").val(),
                                e_id:$("#e_id").val(),
                                area_id:$("#area_id").val()
                            },
                            done: function (res, curr, count) {
                                //alert() 数据渲染完的方法
                                layer.photos({
                                    photos: '.layer-photos'
                                    , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                                });
                                //将合计数值去小数点
                                $(".layui-table-total div").each(function (i,item) {
                                    var div_text = $(item).html();
                                    var value; //转换后的值
                                    if(div_text != "") {
                                        value = parseInt(div_text);
                                        if(!isNaN(value)) {
                                            $(item).html(parseInt(div_text));
                                        }
                                    }
                                });
                            }
                        });
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                }
            });
        }

        //搜索栏队伍
        var eid = $("#e_id").val();
        var roleid = $("#role_id").val();
        if(roleid==3){
            var areaid = $("#area_id").val();
        }
        $.ajax({
            url: "system/constructionTeam/findAreaTeam.json",
            type: "POST",
            data: {
                eid:eid,
                roleid:roleid,
                areaid:areaid
            },
            dataType: "json",
            success: function (ret4) {
                var laytpl = layui.laytpl;
                var rets = { //数据
                    "list4": ret4.data,
                };
                laytpl($("#demo4").html()).render(rets, function (html) {
                    $("#a_name1").html(html);
                });
                form.render();
            },
            error: function (jqXHR, textStatus, errorThrown) {

            }
        });

        //考勤列表
        table.render({
            elem: '#LAY-user-manage',
            id: 'listReload',
            toolbar: '#toolbarDemo',
            title: title,
            url: findAll_url,
            page: true, //开启分页
            limits: [10, 20, 30, 50], //控制多少行一页（默认五条一页）
            totalRow: true,//开启合计行
            defaultToolbar: ['filter', 'print', 'exports'],
            cols: [cols],
            where:{
                a_tid:$("#a_tid").val(),
                role_id:$("#role_id").val(),
                e_id:$("#e_id").val(),
                area_id:$("#area_id").val()
            },
            done: function (res, curr, count) {
                //alert() 数据渲染完的方法
                layer.photos({
                    photos: '.layer-photos'
                    , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                });
                //将合计数值去小数点
                $(".layui-table-total div").each(function (i,item) {
                    var div_text = $(item).html();
                    var value; //转换后的值
                    if(div_text != "") {
                        value = parseInt(div_text);
                        if(!isNaN(value)) {
                            $(item).html(parseInt(div_text));
                        }
                    }
                });
            }
        });
        //上午图片上传
        layui.use('upload', function () {
            var $ = layui.jquery, upload = layui.upload;
            upload.render({
                elem: '#upload1',
                auto: false,
                multiple: false,
                choose: function (obj) {
                    obj.preview(function (index, file, result) {//预读本地文件示例，不支持ie8
                        console.log(JSON.stringify(obj));
                        console.log(JSON.stringify(file));
                        $('#demo1').attr('src', result); //图片链接（base64）
                    });
                }
            });
        });
        //下午图片上传
        layui.use('upload', function () {
            var $ = layui.jquery, upload = layui.upload;
            upload.render({
                elem: '#upload11',
                auto: false,
                multiple: false,
                choose: function (obj) {
                    obj.preview(function (index, file, result) {//预读本地文件示例，不支持ie8
                        console.log(JSON.stringify(obj));
                        console.log(JSON.stringify(file));
                        $('#demo11').attr('src', result); //图片链接（base64）
                    });
                }
            });
        });

        //监听搜索
        form.on('submit(LAY-user-front-search)', function (data) {
            var field = data.field;
            //执行重载
            table.reload('listReload', {
                where: {
                    starttime: field.starttime,
                    endtime: field.endtime,
                    a_name: field.a_name
                },
                page: {
                    curr: 1//重新从第 1 页开始
                }
            });
        });

        //执行laydate
        var startDate = laydate.render({
            elem: '#startTime', //指定元素
            done: function(value, date){
                // 结束时间大于开始时间
                if( value !== '' ){
                    endDate.config.min.year = date.year;
                    endDate.config.min.month = date.month - 1;
                    endDate.config.min.date = date.date;
                }else{
                    endDate.config.min.year = '';
                    endDate.config.min.month = '';
                    endDate.config.min.date = '';
                }
            }
        });
        //执行laydate
        var endDate = laydate.render({
            elem: '#endTime', //指定元素
            done:function (value,date) {
                //  开始时间小于结束时间
                if( value !== '' ){
                    startDate.config.max.year = date.year;
                    startDate.config.max.month = date.month - 1;
                    startDate.config.max.date = date.date;
                }else{
                    startDate.config.max.year = '';
                    startDate.config.max.month = '';
                    startDate.config.max.date = '';
                }
            }
        });

        //初始化考勤信息列表修改页面
        function loadData(data) {
            var ret = {
                "id": data.id,
                "a_createDate": data.a_createDate,
                "a_am_num": data.a_am_num,
                "a_pm_num": data.a_pm_num,
                "a_should_num": data.a_should_num,
                "a_am_picture": data.a_am_picture,
                "a_pm_picture": data.a_pm_picture,
                "a_am_createDate": data.a_am_createDate,
                "a_pm_createDate": data.a_pm_createDate,
            };
            $("#demo1").attr("src", data.a_am_picture);
            $("#demo11").attr("src", data.a_pm_picture);
            $('#a_createDate').attr("disabled","disabled");
            $('#a_createDates').val(data.a_createDate);
            $("#am").show();
            $("#a_pm").show();//修改考勤 显示下午考勤
            if(null==data.a_pm_createDate){
                $("#pm").hide();
            }
            return ret;
        }

        //初始化日期模块
        laydate.render({
            elem: '#createDate' //指定元素
        });

        //弹出修改页面调用初始化数据方法
        function initUpdate(data) {
            var a = layer.open({
                type: 1,
                title: title,
                content: $('#layuiadmin-form-useradmin'),
                btn: [], //可以无限个按钮
                area:["600px","600px"],
                cancel: function (index, layero) {//取消事件
                    location.replace(location.href);　//layer.open关闭刷新
                },
                success: function (layero, index) {
                    var myDate = new Date;
                    var year = myDate.getFullYear(); //获取当前年
                    var mon = myDate.getMonth() + 1; //获取当前月
                    var date = myDate.getDate(); //获取当前日
                    var thisdate = year+'-'+mon+'-'+date;
                    var a_date = laydate.render({
                        elem: '#a_createDate'
                        ,min: thisdate//最小日期
                        ,max: thisdate//最大日期
                        ,value: thisdate//初始日期
                        ,isInitValue: true//是否开启初始赋值
                        // ,ready: function(){
                        //     a_date.hint('日期可选值设定在 <br> <p style="color: green">当日</p>');
                        // }
                    });
                    //赋值施工队伍
                    $("#a_name").val(data.a_name);
                    var a_tid = $("#a_tid").val();
                    var roid= $("#role_id").val();
                    if(roid==4){
                        $.ajax({
                            url: "system/att_management/findTeam.json",
                            type: "POST",
                            data:{
                                a_tid: a_tid,
                                role_id: roid
                            },
                            dataType: "json",
                            success: function(ret){
                                $("#a_name").val(ret.obj.t_name);
                            },
                            error:function(jqXHR, textStatus, errorThrown){

                            }
                        });
                    }
                }
            });
            // layer.full(a);//layer全屏
            //如果是添加则重置表单，如果是编辑则给表单赋值
            if (data == 0 || data == null) {
                $("#id").val("");
                $("#a_pm").hide();//添加考勤 隐藏下午考勤
                $("#am").hide();
                $("#a_pm_num").removeAttr('lay-verify');//移除下午考勤必填
                $("#a_createDate3").attr("name","");
                // $('#myform')[0].reset();
                return;
            } else {
                layui.form.val("component-form-element", loadData(data));
            }

        }

        //修改考勤页面的内容提交到后台处理
        form.on('submit(component-form-element)', function (data) {
            var shouldnum = parseInt(data.field.a_should_num);
            var amnum = parseInt(data.field.a_am_num);
            var t_count;
            //获取当前队伍最大施工人数
            var a_tid = $("#a_tid").val();
            var role_id = $("#role_id").val();
            $.ajax({
                url: "system/att_management/findTeam.json",
                type: "POST",
                data: {
                    a_tid: a_tid,
                    role_id: role_id
                },
                async:false,
                dataType: "json",
                success: function (ret) {
                    if(ret.code==0){
                        t_count  = ret.obj.t_count;
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                }
            });
            var count = parseInt(t_count);
            if(shouldnum>count){
                layer.msg("当前施工队伍最大施工人数为"+count+"人");
                return false;
            }
            if(amnum>shouldnum){//上午人数大于应到人数
                layer.msg("上午考勤人数不得大于应到人数");
                return false;
            }else if(amnum<=shouldnum){//上午人数小于等于应到人数
                postUpdate(data);
                return false;
            }
            if(data.field.a_pm_num!=""){
                var pmnum = parseInt(data.field.a_pm_num);
                if(pmnum>shouldnum){
                    layer.msg("下午考勤人数不得大于应到人数");
                    return false;
                }else if(pmnum<=shouldnum){
                    postUpdate(data);
                    return false;
                }
            }
            return false;
        });
        //头工具栏事件
        table.on('toolbar(LAY-user-manage)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'add':
                    initUpdate(0);
                    break;
                case 'delete':
                    var data = checkStatus.data;
                    if (data.length > 0) {
                        //var id = new Array(); //声明数组
                        for (var i in data) {
                            var a = data[i].id; //得到复选框的值
                            postDelete(a);
                        }
                    } else {
                        layer.msg("至少选择一个进行删除");
                    }
                    break;
                case 'export':
                    layer.msg("导出");
                    break;
            }
        });

        //点击每行右工具栏“操作”里面按钮效果
        table.on('tool(LAY-user-manage)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                layer.confirm('删除以后数据将不能恢复，确定删除吗？', function(index) {
                    postDelete(data.id);
                });
            }else if (obj.event === 'edit') {
                initUpdate(data);
            }
        });


        //ajax提交删除内容
        window.postDelete = function (id) {
            AjaxCommon.ajax(delete_url, "post", "json", {"id": id}, function (ret) {
                if (ret == null) {
                    layer.msg("删除失败", {
                        icon: 5
                    });
                } else {
                    layer.msg(ret.msg, {time: 600, icon: 6}, function () {
                        location.replace(location.href);
                    });
                    layer.closeAll();
                    // table.reload('listReload');
                }
                return ret;
            });
        };

        //ajax提交添加考勤
        window.postUpdate = function (data) {
            var formData = new FormData();

            formData.append("data", JSON.stringify(data.field));
            if($("input[name='file']")[0].files[0]!=undefined){
                formData.append("file", $("input[name='file']")[0].files[0]);
            }
            if($("input[name='file']")[1].files[0]!=undefined){
                formData.append("file1", $("input[name='file']")[1].files[0]);
            }
            $.ajax({
                url: update_url,
                type: "POST",
                //traditional:true,
                data: formData,
                processData: false,
                contentType: false,
                success: function (data) {
                    if (data.code == 0) {
                        layer.closeAll();
                        layer.msg(data.msg, {time: 600, icon: 1}, function () {
                            location.replace(location.href);
                        });
                    } else {
                        layer.msg(data.msg, {icon: 5});
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    var estr = "Page:" + window.location.pathname + ",Function:postUpdate()";
                    layer.open({
                        title: "错误信息",
                        type: 2,
                        content: "base/error.jhtml?info=" + estr,
                        btn: ['关闭'] //可以无限个按钮
                    });
                }
            });
        }
    });

</script>

</body>

</html>
